class GlobalState {
    private static instance: GlobalState;
    private action: any;
    private setGlobalStateFunc: any;
    private onGlobalStateChangeFunc: any;
    private static isInitialized: boolean = false;

    private constructor() {
        if (GlobalState.instance) {
            throw new Error("这是一个全局单例,请通过getInstance获取实例");
        }
        this.action = null;
        this.setGlobalStateFunc = null;
        this.onGlobalStateChangeFunc = null;
    }

    static initGlobalState(action: any, setGlobalState: any, onGlobalStateChange: any): void {
        if (GlobalState.isInitialized) {
            // throw new Error("GlobalState已经初始化过了");
            console.error("GlobalState已经初始化过了")
            return;
        }
        // GlobalState.instance = new GlobalState();
        GlobalState.getInstance(action, setGlobalState, onGlobalStateChange);
        GlobalState.isInitialized = true;
    }

    static getInstance(action?: any, setGlobalState?: any, onGlobalStateChange?: any): GlobalState {
        if (!GlobalState.instance) {
            if (!action || !setGlobalState || !onGlobalStateChange) {
                throw new Error("GlobalState未初始化，请先调用initGlobalState方法");
            }
            GlobalState.instance = new GlobalState();
            GlobalState.instance.action = action;
            GlobalState.instance.setGlobalStateFunc = setGlobalState;
            GlobalState.instance.onGlobalStateChangeFunc = onGlobalStateChange;
        }
        return GlobalState.instance;
    }

    setGlobalState(value: any): void {
        this.setGlobalStateFunc(value);
    }

    onGlobalStateChange(fn: any): void {
        // this.onGlobalStateChangeFunc(fn);
        console.log('是否有值', GlobalState.instance);
        GlobalState.instance.onGlobalStateChangeFunc(fn, true);
    }
}

export default GlobalState;





/** 使用方式
// 在应用初始化时（比如在入口文件中）只需调用一次：
GlobalState.initGlobalState(action, setGlobalState, onGlobalStateChange);

// 在其他地方使用时，直接调用：
const globalState = GlobalState.getInstance();
globalState.setGlobalState(someValue);

 */
